<template>
    <div class="local-play-list-container">

        <!-- 本地列表导航 -->
        <div class="local-play-list-nav">

            <!-- 自动输入框 -->
            <n-auto-complete class="local-play-list-nav-btn" v-model:value="inputValue" :input-props="{ autocomplete: 'disabled' }" clearable :options="options" :on-select="selectOneAudio" placeholder="请输入要搜的本地歌手、本地音乐" />

            <!-- 随机播放 -->
            <n-button class="local-play-list-nav-btn" type="tertiary" @click="playLocalPlayListRandom">开始播放</n-button>

            <!-- 清空列表 -->
            <n-popconfirm class="n-popover-clear-localplaylist" @positive-click="handleLocalPlayListPositiveClick">
                <template #trigger>
                    <n-button style="margin-right: 10px;" type="tertiary">
                        <template #icon>
                            <n-icon>
                                <Error />
                            </n-icon>
                        </template>
                        清空列表
                    </n-button>
                </template>
                删除列表后将不可恢复，是否确认？
            </n-popconfirm>

            <!-- 添加多个文件 -->
            <n-upload class="local-play-list-nav-btn" @change="importSoundFiles" :show-file-list="false" accept="audio/*" multiple>
                <n-button type="tertiary">
                    <template #icon>
                        <n-icon>
                            <MusicAdd />
                        </n-icon>
                    </template>
                    添加本地音乐
                </n-button>
            </n-upload>

            <!-- 添加文件夹 -->
            <n-upload class="local-play-list-nav-btn" @change="importSoundDirectory" :show-file-list="false" accept="audio/*" directory multiple>
                <n-button type="tertiary">
                    <template #icon>
                        <n-icon>
                            <DocumentImport />
                        </n-icon>
                    </template>
                    添加本地文件夹
                </n-button>
            </n-upload>

        </div>

        <!-- 本地列表清单 -->
        <div class="local-play-list-conent">
            <n-list class="local-play-list" clickable hoverable v-if="usePlayList.localPlayList.length != 0">
                <template #header>
                    本地播放列表（{{ usePlayList.localPlayList.length }}）
                    <n-gradient-text
                        :gradient="`linear-gradient(${useSystemConfig.musicListFontColorDeg}deg, ${useSystemConfig.musicListFontColorStrat} 0%, ${useSystemConfig.musicListFontColorMiddle} 50%, ${useSystemConfig.musicListFontColorEnd} 100%)`"
                        style="user-select: none;">
                        - - - 统计于{{ moment().format('YYYY-MM-DD HH:mm:SS') }} - - -
                    </n-gradient-text>
                </template>
                <n-scrollbar style="max-height: calc(100vh - 255px)">
                    <n-list-item v-for="(item, index) in usePlayList.localPlayList" :key="index" @dblclick="playLocalAudio(item.audioName, item.audioSrc, item.audioCover, index)">

                        <template #prefix>
                            <n-button v-if="item.play" text>
                                <template #icon>
                                    <n-icon>
                                        <svg class="icon" aria-hidden="true">
                                            <use xlink:href="#icon-youjiantou"></use>
                                        </svg>
                                    </n-icon>
                                </template>
                            </n-button>
                            <n-button v-if="!item.play" text>
                                <template #icon>
                                    <n-icon>
                                    </n-icon>
                                </template>
                            </n-button>
                        </template>

                        <div class="audioInfo">
                            <div class="audioInfoItem">
                                <n-gradient-text
                                    :gradient="`linear-gradient(${useSystemConfig.musicListFontColorDeg}deg, ${useSystemConfig.musicListFontColorStrat} 0%, ${useSystemConfig.musicListFontColorMiddle} 50%, ${useSystemConfig.musicListFontColorEnd} 100%)`"
                                    style="user-select: none;">
                                    {{ (index + 1) + '. ' + item.audioName }}
                                </n-gradient-text>
                            </div>
                            <div class="audioInfoItem">
                                <n-gradient-text
                                    :gradient="`linear-gradient(${useSystemConfig.musicListFontColorDeg}deg, ${useSystemConfig.musicListFontColorStrat} 0%, ${useSystemConfig.musicListFontColorMiddle} 50%, ${useSystemConfig.musicListFontColorEnd} 100%)`"
                                    style="user-select: none;">
                                    {{ item.duration }}
                                </n-gradient-text>
                            </div>
                            <div class="audioInfoItem">
                                <n-gradient-text
                                    :gradient="`linear-gradient(${useSystemConfig.musicListFontColorDeg}deg, ${useSystemConfig.musicListFontColorStrat} 0%, ${useSystemConfig.musicListFontColorMiddle} 50%, ${useSystemConfig.musicListFontColorEnd} 100%)`"
                                    style="user-select: none;">
                                    {{ bytesToSize(item.size) }}
                                </n-gradient-text>
                            </div>
                        </div>

                        <template #suffix>
                            <n-button text @click="deleteLocalPlayList(index)">
                                <template #icon>
                                    <n-icon :component="Delete20Regular" />
                                </template>
                            </n-button>
                        </template>

                    </n-list-item>
                </n-scrollbar>
            </n-list>
        </div>

    </div>
</template>
    
<script setup lang='ts'>
import { Delete20Regular } from "@vicons/fluent";
import { Error, DocumentImport, MusicAdd } from "@vicons/carbon";
import { UploadFileInfo, useMessage } from "naive-ui";
import { onUnmounted, getCurrentInstance, ref, computed } from 'vue';
import { usePlayListStore, usePlayConfigStore } from "../../store";
import { matchLocalMusicExt, bytesToSize } from '../../util/calculate'
import { useSystemConfigStore } from '../../store/index'
import moment from 'moment'

onUnmounted(() => {

})

const message = useMessage()
const instance = getCurrentInstance()
const usePlayList = usePlayListStore()
const usePlayConfig = usePlayConfigStore()
const useSystemConfig = useSystemConfigStore()
const inputValue = ref('')

// 自动填充框逻辑
const options = computed(() => {
    if (inputValue.value == '') {
        return usePlayList.localPlayList.map(item => {
            return {
                label: item.audioName.split('.')[0],
                value: item.audioName.split('.')[0]
            }
        })
    } else {
        const reg = new RegExp(inputValue.value, 'ig')
        const array: any[] = []
        for (let index = 0; index < usePlayList.localPlayList.length; index++) {
            const element = usePlayList.localPlayList[index];
            if (reg.test(element.audioName)) {
                array.push({
                    label: element.audioName.split('.')[0],
                    value: element.audioName.split('.')[0]
                })
            }
        }
        return array
    }
})
// 选中填充内容事件
const selectOneAudio = (value) => {
    const reg = new RegExp(value)
    let index = 0
    let audioSrc = ''
    let audioCover = ''
    let audioName = ''
    for (let _index = 0; index < usePlayList.localPlayList.length; _index++) {
        const element = usePlayList.localPlayList[_index];
        if (reg.test(element.audioName)) {
            index = _index
            audioSrc = element.audioSrc
            audioCover = element.audioCover
            audioName = element.audioName
            break;
        }
    }
    usePlayConfig.changeIndex(index)
    usePlayConfig.changeAudioName(audioName)
    usePlayConfig.changeAudioSrc(audioSrc)
    usePlayConfig.changeAudioCover(audioCover)
    usePlayList.positionAudioInPlayList(usePlayConfig.playListMode, index)
    // 提交一个本地播放事件
    instance?.proxy?.$Bus.emit('playLocalAudio', { playListMode: 'localPlayList', audioSrc, index })
}

// 导入本地文件
const importSoundFiles = async (options: { file: UploadFileInfo, fileList: Array<UploadFileInfo>, event?: Event }) => {
    const auth = matchLocalMusicExt(options)
    if (!auth) {
        const file = options.fileList[`${options.fileList.length - 1}`]
        message.warning(`${file.name}不符合的音频格式`)
    }
}
// 导入本地文件夹
const importSoundDirectory = (options: { file: UploadFileInfo, fileList: Array<UploadFileInfo>, event?: Event }) => {
    const auth = matchLocalMusicExt(options)
    if (!auth) {
        const file = options.fileList[`${options.fileList.length - 1}`]
        message.warning(`${file.name}不符合的音频格式`)
    }
}

// 删除对应的本地列表
const deleteLocalPlayList = (index: number) => {
    usePlayList.deleteLocalPlayList(index)
}

// 播放本地音乐
const playLocalAudio = (audioName: string, audioSrc: string, audioCover: string, index: number) => {

    // 播放列表切换至本地、缓存本地播放地址、缓存播放列表数组下标
    usePlayConfig.changeAudioName(audioName)
    usePlayConfig.changeAudioCover(audioCover)
    usePlayConfig.changeAudioSrc(audioSrc)
    usePlayConfig.changeIndex(index)
    // 清除上次播放列表的定位
    usePlayList.resetPositionAudioInPlayList(usePlayConfig.playListMode)
    // 提交一个本地播放事件
    instance?.proxy?.$Bus.emit('playLocalAudio', { playListMode: 'localPlayList', audioSrc, index })

}

// 随机播放本地音乐
const playLocalPlayListRandom = () => {

    if (usePlayList.localPlayList.length == 0) return

    // 播放列表切换至乐库、缓存乐库播放地址、缓存播放列表数组下标
    const index = Math.floor(Math.random() * usePlayList.localPlayList.length)
    usePlayConfig.changeAudioId(usePlayList.localPlayList[index].audioId)
    usePlayConfig.changeAudioName(usePlayList.localPlayList[index].audioName)
    usePlayConfig.changeAudioCover(usePlayList.localPlayList[index].audioCover)
    usePlayConfig.changeAudioSrc(usePlayList.localPlayList[index].audioSrc)
    usePlayConfig.changeIndex(index)
    // 清除上次播放列表的定位
    usePlayList.resetPositionAudioInPlayList(usePlayConfig.playListMode)
    // 提交一个乐库播放事件
    instance?.proxy?.$Bus.emit('playLocalAudio', { playListMode: 'localPlayList', audioSrc: usePlayList.localPlayList[index].audioSrc, index: index })

}

// 清空列表确认
const handleLocalPlayListPositiveClick = () => {
    usePlayList.resetLocalPlayList()
}


</script>
    
<style scoped lang="less">
.local-play-list-container {
    display: flex;
    flex-wrap: wrap;
    height: calc(100vh - 120px);
    margin-top: 10px;

    .local-play-list-nav {
        display: flex;
        height: 35px;
        width: 100%;
        margin-bottom: 5px;
        justify-content: center;

        .local-play-list-nav-btn {
            margin-right: 10px;

            &:nth-child(3) {
                width: 140px;
            }

            &:nth-child(4) {
                width: 140px;
            }
        }

    }

    .local-play-list-conent {
        width: 100%;
        height: calc(100vh - 165px);

        .local-play-list {
            width: 100%;
            height: calc(100vh - 165px);

            .audioInfo {
                width: 100%;
                display: flex;
                justify-content: space-around;

                .audioInfoItem:nth-child(1) {
                    width: 50%;
                }

                .audioInfoItem:nth-child(2) {
                    width: 25%;
                }

                .audioInfoItem:nth-child(3) {
                    width: 25%;
                }
            }
        }

    }
}
</style>